package rs.udd.web.controller;

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import rs.udd.exceptions.UddException;
import rs.udd.model.Advert;
import rs.udd.model.Category;
import rs.udd.service.AdvertService;
import rs.udd.service.BrowseService;
import rs.udd.service.CategoryService;
import rs.udd.service.dto.browse.BrowseDto;

@Controller
@RequestMapping({ "browse", "/browse", "/browse/" })
public class BrowseController {

	private final Logger LOGGER = LogManager.getLogger(getClass());

	@Autowired
	private CategoryService categoryService;

	@Autowired
	private AdvertService advertService;
	
	@Autowired
	private BrowseService browseService;

	@RequestMapping(method = RequestMethod.GET)
	public String getBrowse(Model model) {
		LOGGER.info("Browsing...");
		BrowseDto dto = browseService.prepareBrowse();
		model.addAttribute("adverts", dto.getAdverts());
		model.addAttribute("categories", dto.getCategories());
		
		return "common/browse";
	}

	@RequestMapping(value = "/{categoryName}", method = RequestMethod.GET)
	public String viewCategory(Model model, @PathVariable String categoryName) {

		LOGGER.info("Viewing category: " + categoryName);

		try {
			Category category = categoryService.findCategoryByName(categoryName);
			List<Advert> adverts = advertService.findAdvertsByCategory(categoryName);

			model.addAttribute("category", category);
			model.addAttribute("adverts", adverts);

			return "common/browseCategory";
		} catch (UddException e) {
			LOGGER.error("Error while viewing category " + categoryName, e);
			model.addAttribute("message", e.getMessage());
			return "error/error";
		}
	}

}
